import { useEffect, useState, useRef, useImperativeHandle } from 'react'
/* -------------------------------------------------------- Declare -- */
const { $lazy, $, $fn } = window
/* -------------------------------------------------------- Async Component -- */
const SearchForm = $lazy.hook(()=>import('#cpt/form/search-form'))
const Table = $lazy.hook(()=>import('@antd/table'))
const Page = $lazy.load(()=>import('#tp/content/page-content'))
const Box = $lazy.load(()=>import('#tp/box/box'))
// const getApi = () => {
// 	let url = window.location.href
// 	let index = url.indexOf('?')
// 	if( index > 0 ) url = url.substring(0, index)
// 	url = url.match(/([^/]+)$/)
// 	url = $fn.hasArray( url ) ? url[1] : null
// 	url = url.includes('-') ? url.replace(/-/g, '_') : url
// 	return url
// }
const getRouterInfo = () => {
	let hash = window.location.hash
	let path = hash ? hash.replace('#','') : window.location.pathname
	let data = $fn.session('menu')
	let obj = {}
	const deep = data => {
		for( let i in data ){
			let v = data[i]
			if(v.path === path){
				obj = v
				break
			}else{
				deep(v.children)
			}
		}
	}
	deep(data)
	$fn.session('present', obj)
	if( obj?.name ){
		if( obj.name.includes('-') ) obj.name = obj.name.replace(/-/g, '_')
		if( !obj.name.startsWith('dict_') && path.includes('/dict/') ) obj.api = 'dict/' + obj.name
	}
	return obj
}
/* -------------------------------------------------------- Page Component -- */
const Index = ({ page, box, search, table, height, className, style, onTableRef, isModalTable, auto }, ref) => {
	const [ loading, setLoading ] = useState()
	const [ keys, setKeys ] = useState(table?.row?.keys ?? [])
	const [ rows, setRows ] = useState()
	const tableRef = useRef()
	const searchRef = useRef()
	const currentKeys = useRef()
	if( ( ( table && !table?.api ) || ( page && !page?.title) ) && (auto != false || auto !== 0)) {
		const { api, name, title, perm } = getRouterInfo()
		if( !table?.api ) table.api = api || name
		if( !page?.title ) page.title = title
		if( table && perm ) table.perm = perm
		if( page && perm ) page.perm = perm
	}else{
		const { perm } = getRouterInfo()
		if( table && perm ) table.perm = perm
		if( page && perm ) page.perm = perm
	}
	const globalObject = {
		clearKeys: () => {
			if(table?.row?.is_rows) {
				if($fn.hasArray(currentKeys.current)){
					setKeys([])
					setRows({})
				}
			}
		},
		refreshRows: () => {
			if(table?.row?.is_rows) {
				setTimeout(()=>{
					let row = $.ref(tableRef).rows()
					const rows = table?.row?.type === 1 ? row : row[row.length - 1]
					setRows(rows)
				})
			}
		}
	}
	useEffect(()=>{ currentKeys.current = keys }, [keys])
	
	/* --------------------------- 搜索配置 --------------------------- */
	const searchConfig = $fn.hasObject(search) ?  {
		loading,
		onSubmit: option => $.ref(tableRef)?.search?.( option ),
		onReset : () => $.ref(tableRef)?.reset?.(),
		...search
	} : null
	/* --------------------------- 表格配置 --------------------------- */
	const tableConfig = $fn.hasObject(table) ? {
		global:globalObject,
		search,
		isModalTable,
		tableRef: () => $.ref(tableRef),
		searchRef: () => $.ref(searchRef),
		keys,
		onKeysChange: (keys, rows) => {
			setKeys(keys)
			if(table?.row?.is_rows) setRows(rows)
		},
		...table,
		onLoading: v => setLoading(v),
		onRef:onTableRef
	} : null
	/* --------------------------- 页面配置 --------------------------- */
	const pageConfig = $fn.hasObject(page) ? {
		// refresh:true,
		table: tableConfig,
		keys,
		rows,
		contentClass:'plr10',
		loading,
		global:globalObject,
		...page,
	} : null
		/* --------------------------- 盒子配置 --------------------------- */
	const boxConfig = $fn.hasObject(table) ? {
		table: tableConfig,
		keys,
		contentClass:'plr10',
		loading,
		...box
	} : null
	
	useImperativeHandle( ref, () => ({
		searchRef: () => $.ref(searchRef),
		tableRef: () => $.ref(tableRef)
	}))
	
	const SearchTableComponent = (
		<>
			{ (search && !search.hide) && <SearchForm ref={searchRef} {...searchConfig} /> }
			{ table && <Table ref={tableRef} {...tableConfig} />}
		</>
	)
	
	if( page ){
		return <Page {...pageConfig}>{ SearchTableComponent }</Page>
	}else if( box ){
		return <Box {...boxConfig}>{ SearchTableComponent }</Box>
	}else{
		return <div className={`fv ex h ${$.css(className)}`} style={{height,...style}}>{ SearchTableComponent }</div>
	}
}
export default Index